/*
这个文件是支持，静态路由，和预览中动态路由的集合体
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  //console.log('from: ' + from.path + ' to: ' + to.path)
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // //console.log('hasToken:' + hasToken)
  //
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({path: '/'})
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const roles = store.getters.roles
      const isLoadedMenus = store.getters.isLoadedMenus
      if (!isLoadedMenus) {
        try{
          // clear routes
          await store.dispatch('permission/clearRoutes')

          // generate accessible routes map based on roles
          const previewRoutes = await store.dispatch('permission/generatePreviewRoutes', roles)
          const accessRouteskTmp = await store.dispatch('permission/generateRoutes', roles)
          const accessRoutes = previewRoutes.concat(accessRouteskTmp)

          // //console.log("======== accessRoutes =========")
          // //console.log(accessRoutes)

          const formatRouter = (routes, newRoutes = []) => {
              routes.map(item => {
                  if (item.children && item.children.length > 0) {
                      formatRouter(item.children, newRoutes);
                  }else {
                      newRoutes.push(item);
                  }
              })
              return newRoutes;
          }

          let newRoutes = []
          accessRoutes.forEach( item => {
              if (item.children && item.children.length > 0) {
                  let sonRouters = formatRouter(item.children);
                  let tmpRouters = Object.assign({}, item)
                  tmpRouters.children = sonRouters
                  newRoutes.push(tmpRouters);
              }else {
                  newRoutes.push(item);
              }
          })

          // //console.log(newRoutes)
          router.addRoutes(newRoutes)

          // modify isLoadedMenus = true
          await store.dispatch('user/loadedMenus')

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({...to, replace: true})
        }catch (e) {
          //console.log(e)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next()
      }
      /* if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          //console.log('roles:' + roles)

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }*/
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

/**
 * 自定义查找字段, 根据最后一级某个字段查找完整树(整个父类)
 * @param {*} val     要查找对比的值
 * @param {*} data    要查找的数据
 * @param {*} fKey    要查找对比的字段
 */
const recursiveTreeByLastLevel = (val, data, fKey = 'value') => {
  let rData = [];
  for (let i = 0, len = data.length; i < len; i++) {
    rData.push(data[i]);
    if (data[i].children && data[i].children.length > 0) {
      rData = rData.concat(recursiveTreeByLastLevel(val, data[i].children, fKey));
      if (rData.some(item => item[fKey] === val)) return rData;
    }
    if (data[i][fKey] === val) return rData;
    rData = [];
  }
  return rData;
}
router.afterEach((to, from, next) => {
  // finish progress bar
  NProgress.done()
  const routerCrumbList = recursiveTreeByLastLevel(to.name, store.getters.permission_routes, 'name')
  store.dispatch('permission/setCrumbList', routerCrumbList) // 通过vuex缓存
})

/*

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
*/
